package com.erci.controller.admin;

import com.erci.result.Result;
import com.erci.utils.AliOssUtil;
import jakarta.servlet.annotation.MultipartConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@CrossOrigin(origins = "http://localhost:5173")
@RestController
@RequestMapping("/admin/api")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 1,  // 1MB
        maxFileSize = 1024 * 1024 * 10,       // 10MB
        maxRequestSize = 1024 * 1024 * 15     // 15MB
)
@Slf4j
public class UploadController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @PostMapping("/load")
    public Result<Map<String, String>> upload(@RequestParam("file") MultipartFile file) {
        log.info("图片上传 ");
        try {
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uuid = UUID.randomUUID().toString();
            String objectName = uuid + System.currentTimeMillis() + suffix;
            //上传文件
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(Map.of("url", filePath));
        } catch (IOException e) {
            log.info("上传失败");
        }
        return Result.error("上传失败");
    }
}
